import { defineStore } from 'pinia'

export const useUserStore = defineStore('user', {
  state: () => ({
    user: null,
    token: {
      accessToken: null,
      refreshToken: null
    }
  }),

  actions: {
    setToken(newToken) {
      // 确保同时更新 accessToken 和 refreshToken
      this.token = {
        accessToken: newToken.accessToken,
        refreshToken: newToken.refreshToken // 确保包含刷新令牌
      }
      // 确保立即写入存储
      if (process.client) {
        localStorage.setItem('user-store', JSON.stringify({
          user: this.user,
          token: this.token
        }))
      }
    },

    setUser(userData) {
      this.user = userData
    },

    logout() {
      this.$reset()
      if(process.client){
        localStorage.removeItem('user')
        localStorage.removeItem('token')
      }
    },
    clearUser() {
      this.user = null
      this.token = null
      localStorage.removeItem('user-store')
    }
  },

  persist: {
    key: 'user-store',
    paths: ['user', 'token'],
    storage:{
      getItem: (key) => process.client ? localStorage.getItem(key) : null,
      setItem: (key, value) => process.client ? localStorage.setItem(key, value) : null,
      removeItem: (key) => process.client ? localStorage.removeItem(key) : null
    }
  }
})